package com.zhou.JavaAndroidFirm.model;

import com.jaydenxiao.androidfire.bean.VideoData;
import com.zhou.JavaAndroidFirm.constract.VideoListContract;
import com.zhou.JavaAndroidFirm.http.ApiConstants;
import com.zhou.JavaAndroidFirm.http.HttpService;
import com.zhou.JavaAndroidFirm.http.HttpUtils;
import com.zhou.JavaAndroidFirm.rx.RxSchedulers;
import com.zhou.JavaAndroidFirm.utils.TimeUtil;

import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;

/**
 * @author Administrator
 * @date 2018/7/18 0018
 * @des
 */
public class VideoListModel implements VideoListContract.Model {

    @Override
    public Observable<List<VideoData>> getVideosListData(final String type, int startPage) {
        return HttpUtils.getInstance()
                .getRetofitClinet()
                .setBaseUrl(ApiConstants.NETEAST_HOST_BASEURL)
                .builder(HttpService.class)
                .getVideoList(type, startPage)
                .flatMap(new Func1<Map<String, List<VideoData>>, Observable<VideoData>>() {
                    @Override
                    public Observable<VideoData> call(Map<String, List<VideoData>> stringListMap) {
                        return Observable.from(stringListMap.get(type));
                    }
                })
                .map(new Func1<VideoData, VideoData>() {
                    @Override
                    public VideoData call(VideoData videoData) {
                        videoData.setPtime(TimeUtil.formatDate(videoData.getPtime()));
                        return videoData;
                    }
                })
                .distinct()
                .toSortedList(new Func2<VideoData, VideoData, Integer>() {
                    @Override
                    public Integer call(VideoData videoData, VideoData videoData2) {
                        return videoData2.getPtime().compareTo(videoData.getPtime());
                    }
                })
                .compose(RxSchedulers.<List<VideoData>>io_main())
                ;
    }
}
